<template>
  <view class="collection-page">
    <!-- 顶部导航 -->
    <view class="top-nav">
      <!-- 返回按钮 -->
      <view class="back-btn" @click="navigateBack">
        <image 
          class="back-icon" 
          src="/static/icons/left.png" 
          mode="widthFix"
        ></image>
      </view>
      <!-- 标题 -->
      <text class="page-title">职位收藏</text>
    </view>

    <!-- 收藏列表 -->
    <view class="collection-list">
      <!-- 加载中状态 -->
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      
      <!-- 空状态 -->
      <view v-if="!loading && collectionData.length === 0" class="empty">
        <image 
          src="/static/icons/empty-collection.png" 
          mode="widthFix" 
          class="empty-img"
        ></image>
        <text class="empty-text">暂无收藏的职位</text>
      </view>
      
      <!-- 列表内容 -->
      <block v-for="(item, index) in collectionData" :key="item.collectionId">
        <view class="collection-item">
          <!-- 职位+薪资 -->
          <view class="item-top">
            <text class="position">{{ item.recruitInfoDO.recruitName }}</text>
            <text class="salary">{{ setSalary(item.recruitInfoDO.startSalary,item.recruitInfoDO.maxSalary,item.recruitInfoDO.payMethod) }}</text>
          </view>

          <!-- 公司+技能需求 -->
          <text class="company">{{ item.companyDO.companyName }}</text>
          <text class="skill-request">{{ item.recruitInfoDO.skillRequest }}</text>

          <!-- HR信息+按钮区 -->
          <view class="hr-section">
            <view class="hr-info">
              <image 
                class="hr-avatar" 
                :src="item.hrDO.headIcon || '/static/avatar/avatar.png'" 
                mode="aspectFill"
              ></image>
              <text class="hr-name">{{ item.hrDO.hrName }} HR</text>
            </view>
            <!-- 按钮容器 -->
            <view class="btn-group">
              <button class="contact-btn" @click="handleContact(item)">立即沟通</button>
              <button class="uncollect-btn" @click="handleUncollect(item.collectionId)">取消收藏</button>
            </view>
          </view>
        </view>
      </block>
    </view>
  </view>
</template>

<script>
import state from '../../store/state';
import { selectCollect, deleteCollect } from '@/api/collect.js'; // 引入删除接口

export default {
  data() {
    return {
      collectionData: [],
      loading: false,
      userId: null // 从store获取的当前登录用户ID
    };
  },
  onLoad() {
    // 先加载用户信息，再获取收藏列表（确保userId有值）
    this.loadUserInfo();
  },
  methods: {
	  setSalary(startSalary, maxSalary, payMethod) {
	    if (payMethod === 4) {
	      return `面议`;
	    }
	    if (payMethod === 0) {
	      if (maxSalary === null) return `${startSalary}/日 起`;
	      if (startSalary === null) return `最高 ${maxSalary}/日`;
	      return `${startSalary} ~ ${maxSalary}/日`;
	    }
	    if (payMethod === 1) {
	      if (maxSalary === null) return `${startSalary}/周 起`;
	      if (startSalary === null) return `最高 ${maxSalary}/周`;
	      return `${startSalary} ~ ${maxSalary}/周`;
	    }
	    if (payMethod === 2) {
	      if (maxSalary === null) return `${startSalary}/月 起`;
	      if (startSalary === null) return `最高 ${maxSalary}/月`;
	      return `${startSalary} ~ ${maxSalary}/月`;
	    }
	    if (payMethod === 3) {
	      if (maxSalary === null) return `${startSalary}/时 起`;
	      if (startSalary === null) return `最高 ${maxSalary}/时`;
	      return `${startSalary} ~ ${maxSalary}/时`;
	    }
	    return '薪资面议'; // 默认值
	  },
	  
	  truncateText(text) {
	    if (text && text.length > 20) {
	      return text.substring(0, 20) + '...';
	    }
	    return text || '';
	  },
    // 加载用户信息（处理store中userInfo可能延迟的情况）
    loadUserInfo() {
      if (!state.userInfo) {
        // 延迟2秒重试，避免因store数据未加载完成导致userId为空
        setTimeout(() => {
          this.loadUserInfo();
        }, 2000);
        return;
      }
      // 获取用户ID后，立即查询收藏列表
      this.userId = state.userInfo.userId;
      this.getCollectionList();
    },

    // 返回上一页
    navigateBack() {
      uni.navigateBack();
    },

    // 获取职位收藏列表（模仿你的写法：Promise链式调用）
    getCollectionList() {
      this.loading = true;
      selectCollect({ userId: this.userId })
        .then(res => {
			console.log(res)
          this.loading = false; // 无论成功失败，都关闭加载状态
          if (res.code === 200) {
            this.collectionData = res.data; // 赋值后端返回的收藏列表
          } else {
            uni.showToast({ title: '获取收藏列表失败', icon: 'none' });
          }
        })
        .catch(err => {
          this.loading = false;
          console.error('获取收藏列表异常：', err);
          uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' });
        });
    },

    // 立即沟通（跳转聊天页，携带HR ID）
    handleContact(item) {
		console.log(item)
      // 确保item中有hrId（需后端返回该字段）
      if (item.hrDO.hrId) {
        uni.navigateTo({
        	url: `/pages/zj/UserToHRChat?companyId=${item.companyDO.companyId}
			&hrId=${item.hrDO.hrId}&hrName=${item.hrDO.hrName}&companyName=${item.companyDO.companyName}` });
      } else {
        uni.showToast({ title: 'HR信息缺失，无法沟通', icon: 'none' });
      }
    },

    // 取消收藏（合并确认弹窗和删除接口调用，模仿查询的Promise写法）
    handleUncollect(collectionId) {
      // 第一步：显示确认弹窗
      uni.showModal({
        title: '提示',
        content: '确定取消收藏该职位吗？',
        showCancel: true, // 显示取消按钮
        cancelText: '取消',
        confirmText: '确定',
        success: (modalRes) => {
          // 第二步：用户点击确认后，调用删除接口
          if (modalRes.confirm) {
            // 调用删除收藏接口（参数：收藏ID + 用户ID，确保是当前用户的收藏）
            deleteCollect(collectionId)
              .then(res => {
                if (res.code === 200) {
                  // 后端删除成功后，前端同步删除该条数据
                  this.collectionData = this.collectionData.filter(
                    item => item.collectionId !== collectionId
                  );
                  uni.showToast({ title: '取消收藏成功', icon: 'success' });
                } 
              })
          }
        }
      });
    }
  }
};
</script>

<style scoped>
/* 页面容器 */
.collection-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 15px;
}

/* 顶部导航 */
.top-nav {
  display: flex;
  align-items: center;
  height: 44px;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
  background-color: #fff;
  padding: 0 15px;
  position: sticky;
  top: 0;
  z-index: 10;
}
.back-btn {
  width: 44px;
  height: 44px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.back-icon {
  width: 16px;
  height: 16px;
}
.page-title {
  flex: 1;
  text-align: center;
  font-size: 17px;
  font-weight: bold;
  color: #333;
}

/* 收藏列表 */
.collection-list {
  background-color: #f5f5f5;
}

/* 加载中状态 */
.loading {
  text-align: center;
  padding: 30px 0;
  color: #666;
}

/* 空状态 */
.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 50px 0;
}
.empty-img {
  width: 120px;
  height: 120px;
  margin-bottom: 15px;
}
.empty-text {
  color: #999;
  font-size: 14px;
}

/* 列表项 */
.collection-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

/* 职位+薪资 */
.item-top {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 8px;
}
.position {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}
.salary {
  font-size: 14px;
  color: #f56c6c; /* 薪资用红色突出显示 */
  font-weight: 500;
}

/* 公司名称 */
.company {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
  display: block;
}

/* 技能需求 */
.skill-request {
  font-size: 13px;
  color: #999;
  margin-bottom: 12px;
  display: block;
  line-height: 1.5;
}

/* HR信息+按钮区 */
.hr-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}
.hr-info {
  display: flex;
  align-items: center;
}
.hr-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 8px;
  border: 1px solid #eee;
}
.hr-name {
  font-size: 14px;
  color: #333;
}

/* 按钮组 */
.btn-group {
  display: flex;
  gap: 10px;
}
.contact-btn {
  background-color: #007aff;
  color: #fff;
  font-size: 12px;
  padding: 6px 12px;
  border-radius: 4px;
  min-width: 80px;
  height: 28px;
  line-height: 28px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: none;
}
.uncollect-btn {
  background-color: #fff;
  color: #f00;
  border: 1px solid #f00;
  font-size: 12px;
  padding: 6px 12px;
  border-radius: 4px;
  min-width: 80px;
  height: 28px;
  line-height: 28px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>